/*
 * Copyright 2012-2013 Finbudget.com
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package finbudgettable.client.ui.grid.cell.link;

import com.google.gwt.safehtml.shared.UriUtils;
import finbudget.client.ui.table.Record;
import finbudget.shared.process.events.StringPair;

import java.util.List;

/**
 * The class for generating an url from a template string
 */
public class UrlBuilder {

	private final String template;
	private final List<String> params;
	private final List<StringPair> pairParameters;
	/**
	 * Makes link just in case all the required parts found. Otherwise make inconsistent link.
	 */
	private final boolean allLinkFieldsRequired;

	public UrlBuilder(String template, List<String> params, List<StringPair> pairParameters, boolean allLinkFieldsRequired) {
		this.template = template;
		this.params = params;
		this.pairParameters = pairParameters;
		this.allLinkFieldsRequired = allLinkFieldsRequired;
	}

	public String build(Record record) {
		int index = 0;
		String result = template;
		if (pairParameters != null) {
			for (StringPair pair : pairParameters) {
				String value = record.getValueString(pair.getRight());
				if (value == null || value.trim().isEmpty()) {
					value = pair.getLeft();
				}
				result = replaceParam(index, result, value);
				index++;
			}
		} else if (params != null) {
			for (String fieldName : params) {
				String value = record.getValueString(fieldName);
				if (value == null || value.trim().isEmpty()) {
					if (allLinkFieldsRequired) {
						return null;
					}
				}
				result = replaceParam(index, result, value);
				index++;
			}
		}
		return result;
	}

	private String replaceParam(int index, String template, String value) {
		if (template != null) {
			String encodedValue = value != null ? UriUtils.encode(value) : "";
			return template.replaceAll("\\{" + Integer.toString(index) + "\\}", encodedValue);
		}
		return null;
	}

}
